<script setup>
import {
  delApi,
  getAllMenuTreeApi,
  getByIdApi,
  getMenuIdByIdApi,
  getPageApi,
  saveApi,
  updateApi,
  updateMenuApi,
} from "@/api/sysRole";
import { onMounted } from "vue";
import { ref } from "vue";
import $bus from "../../utils/bus";
// ---------------------------------------------------------------------获取查询---------------------------------------------------------------------
const dataList = ref([]);
const queryPageParams = ref({
  pageNumber: 1,
  pageSize: 10,
  roleName: "",
});
const total = ref(0);
const selectedList = ref([]);
const updateShow = ref(true);
const delShow = ref(true);
const getData = async () => {
  const res = await getPageApi(queryPageParams.value);
  dataList.value = res.data.list;
  total.value = res.data.total;
};
const getPage = () => {
  getData();
};
const clear = () => {
  queryPageParams.value.pageNumber = 1;
  queryPageParams.value.pageSize = 10;
  queryPageParams.value.roleName = "";
  getData();
};
const handleSelectionChange = (value) => {
  selectedList.value = value;
  if (value.length == 1) {
    delShow.value = false;
    updateShow.value = false;
  } else if (value.length > 1) {
    updateShow.value = true;
  } else {
    delShow.value = true;
    updateShow.value = true;
  }
};

const handlePageChange = () => {
  getData();
};
// ---------------------------------------------------------------------添加修改---------------------------------------------------------------------
const open = ref(false);
const title = ref("弹出框dialog");
const formRef = ref(null);
const save = async () => {
  open.value = true;
  title.value = "添加角色";
};
const form = ref({
  roleName: "",
  roleDes: "",
});
const formRule = ref({
  roleName: [
    { required: true, message: "不能为空", trigger: "blur" },
    { min: 2, max: 20, message: "长度为2到20", trigger: "blur" },
  ],
});
const colseReset = () => {
  form.value = {
    roleName: "",
    roleDes: "",
  };
};
const closeDialog = () => {
  open.value = false;
  formRef.value.resetFields();
  colseReset();
};
const update = async (id) => {
  open.value = true;
  title.value = "修改人员";
  // console.log(id)
  if (!id) {
    id = selectedList.value[0].id;
  }
  const res = await getByIdApi(id);
  form.value = res.data;
};
const submit = () => {
  if (form.value.id) {
    formRef.value.validate(async (valid) => {
      if (!valid) {
        return;
      }
      const res = await updateApi(form.value);
      ElMessage({
        message: res.data,
        type: "success",
      });
      getData();
      closeDialog();
    });
  } else {
    formRef.value.validate(async (valid) => {
      if (!valid) {
        return;
      }
      const res = await saveApi(form.value);
      ElMessage({
        message: res.data,
        type: "success",
      });
      getData();
      closeDialog();
    });
  }
};

// ---------------------------------------------------------------------删除--------------------------------------------------------------------
const del = (id) => {
  if (!id) {
    id = selectedList.value.map((item) => item.id);
  }
  // console.log(id)
  ElMessageBox.confirm("确认删除？", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await delApi(id);
      ElMessage({
        type: "success",
        message: res.data,
      });
      getData();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
//---------------------------------------------------------------------获取权限列表---------------------------------------------------------------------
const roleId = ref();
const menuOpen = ref(false);
const menuList = ref([]);
const treeRef = ref(null);
const menuSelectIdList = ref([]);
const closeMenuDialog = () => {
  roleId.value = undefined;
  menuOpen.value = false;
  menuList.value = [];
  menuSelectIdList.value = [];
};
const updateMenu = async (id) => {
  menuOpen.value = true;
  const res = await getAllMenuTreeApi();
  menuList.value = res.data;
  const selectIdData = await getMenuIdByIdApi(id);
  menuSelectIdList.value = selectIdData.data;
  roleId.value = id;
};
const menuProps = ref({
  value: "id",
  label: "menuName",
  children: "children",
});

const emnuSubmit = async () => {
  const arr = [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys()];
  const res = await updateMenuApi(roleId.value, arr);
  ElMessage({
    message: res.data,
    type: "success",
  });
  closeMenuDialog()
};
//---------------------------------------------------------------------获取标题事件---------------------------------------------------------------------
const titleData = ref({
  titleFir: "系统管理",
  titleSec: "角色管理",
});

onMounted(() => {
  $bus.emit("title-info", titleData.value);
  getData();
});
</script>
<template>
  <el-card>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="角色名称">
        <el-input placeholder="请输入角色名称" v-model="queryPageParams.roleName" />
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="getPage()">查询</el-button>
        <el-button icon="RefreshRight" type="info" @click="clear()">重置</el-button>
      </el-form-item>
      <br />
      <el-form-item>
        <el-button icon="Plus" plain type="warning" @click="save()">添加</el-button>
        <el-button icon="Edit" plain :disabled="updateShow" type="success" @click="update()"
          >修改</el-button
        >
        <el-button icon="Delete" plain :disabled="delShow" type="danger" @click="del()"
          >删除</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>

  <el-card>
    <!-- 数据展示表格 -->
    <el-table :data="dataList" @selection-change="handleSelectionChange" stripe fit>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column width="75" type="index" label="序号"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDes"></el-table-column>
      <el-table-column fixed="right" width="280" label="操作">
        <template #default="data">
          <el-button icon="Edit" link type="success" size="small" @click="update(data.row.id)"
            >修改</el-button
          >
          <el-button icon="Plus" link type="warning" @click="updateMenu(data.row.id)"
            >配置权限</el-button
          >
          <el-button icon="Delete" link type="danger" size="small" @click="del(data.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="queryPageParams.pageNumber"
      v-model:page-size="queryPageParams.pageSize"
      :page-sizes="[10, 50, 100, 200]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="+total"
      @change="handlePageChange"
    />
  </el-card>

  <el-dialog v-model="open" :title="title" width="50%" :before-close="closeDialog" draggable>
    <el-form :model="form" label-width="auto" :rules="formRule" ref="formRef">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" />
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDes">
        <el-input v-model="form.roleDes" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog()">取消</el-button>
        <el-button type="primary" @click="submit()"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="menuOpen"
    title="权限列表"
    width="50%"
    :before-close="closeMenuDialog"
    draggable
  >
    <el-tree-v2
      ref="treeRef"
      style="max-width: 600px"
      :data="menuList"
      :height="200"
      :props="menuProps"
      show-checkbox
      :default-checked-keys="menuSelectIdList"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog()">取消</el-button>
        <el-button type="primary" @click="emnuSubmit()"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style></style>
